﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;

public partial class frmListaDePresupuestos : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("frmPresupuestos.aspx");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        
        if ((TextBox1.Text.Equals(""))&&(TextBox1.Text.Equals("")))
        {

            String fecha = DateTime.Now.ToString("dd/MM/yyyy");
            string imagepath = Server.MapPath("Img");
            int presup = 0;
            int total = 0;

            this.SqlDataSource2.DataSourceMode = SqlDataSourceMode.DataReader;
            SqlDataReader datos = (SqlDataReader)this.SqlDataSource2.Select(DataSourceSelectArguments.Empty);

            FileStream fs = new FileStream(Server.MapPath("~/") + "PRESUPUESTOS.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle rec3 = new Rectangle(PageSize.A4);
            Document doc = new Document(rec3, 5, 5, 5, 5);
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            iTextSharp.text.Font fontTitle = FontFactory.GetFont("Arial", 18, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font fontHead = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font fontBody = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            Console.WriteLine("");

            Paragraph titulo = new Paragraph("LISTADO DE PRESUPUESTOS AL " + fecha, fontTitle);
            titulo.Alignment = Element.ALIGN_JUSTIFIED;

           
            doc.Open();
            
            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(imagepath + "/logoaf.png");
            doc.Add(logo);
            doc.Add(titulo);
            doc.Add(new Paragraph("  "));
            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(7);
            table.HorizontalAlignment = 0;
            table.TotalWidth = 550f;
            table.LockedWidth = true;
            float[] widths = new float[] { 80f, 110f, 90f, 80f, 60f, 70f, 80f};
            table.SetWidths(widths);

            PdfPCell hnro = new PdfPCell(new Phrase("NRO.PRESUP.", new Font(fontHead)));
            PdfPCell hempresa = new PdfPCell(new Phrase("EMPRESA", new Font(fontHead)));
            PdfPCell hfechapresup = new PdfPCell(new Phrase("FECHA PRESUP.", new Font(fontHead)));
            PdfPCell hdetalle = new PdfPCell(new Phrase("DETALLE", new Font(fontHead)));
            PdfPCell himporte = new PdfPCell(new Phrase("IMPORTE", new Font(fontHead)));
            PdfPCell hestado = new PdfPCell(new Phrase("ESTADO", new Font(fontHead)));
            PdfPCell hvto = new PdfPCell(new Phrase("VENCIMIENTO", new Font(fontHead)));

            table.AddCell(hnro);
            table.AddCell(hempresa);
            table.AddCell(hfechapresup);
            table.AddCell(hdetalle);
            table.AddCell(himporte);
            table.AddCell(hestado);
            table.AddCell(hvto);
            doc.Add(new Paragraph("  "));
            while (datos.Read())
            {
                String numero = datos["nroPresupuesto"].ToString();
                String detalle = datos["detalle"].ToString();
                String razon = datos["razonSocial"].ToString();
                String importe = datos["importe"].ToString();
                String estado = datos["descripcionEstado"].ToString();
                String fechaPresup = datos["fechaPresupuesto"].ToString();
                String vto = datos["fechaValidez"].ToString();

                PdfPCell cnumero = new PdfPCell(new Phrase(numero, new Font(fontBody)));
                PdfPCell cdetalle = new PdfPCell(new Phrase(detalle, new Font(fontBody)));
                PdfPCell crazon = new PdfPCell(new Phrase(razon, new Font(fontBody)));
                PdfPCell cimporte = new PdfPCell(new Phrase(importe, new Font(fontBody)));
                PdfPCell cestado = new PdfPCell(new Phrase(estado, new Font(fontBody)));
                PdfPCell cfechapresup = new PdfPCell(new Phrase(fechaPresup, new Font(fontBody)));
                PdfPCell cvto = new PdfPCell(new Phrase(vto, new Font(fontBody)));


                    table.AddCell(cnumero);
                    table.AddCell(crazon);
                    table.AddCell(cfechapresup);
                    table.AddCell(cdetalle);
                    table.AddCell(cimporte);
                    table.AddCell(cestado);
                    table.AddCell(cvto);
               
                presup = presup + 1;
                int imp = Convert.ToInt32(importe);
                total = total + imp;


            }
            doc.Add(table);
            doc.Add(new Paragraph("  "));
            doc.Add(new Paragraph("  "));
            doc.Add(new Paragraph("TOTAL DE PRESUPUESTOS: " + presup));
            doc.Add(new Paragraph("IMPORTE TOTAL: $" + total));
            doc.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment;filename=PRESUPUESTOS.pdf");
            Response.TransmitFile(Server.MapPath("~/") + "PRESUPUESTOS.pdf");
        }

        
        
        else
        {
        
        
        if(TextBox1.Text.Equals("")||TextBox2.Text.Equals(""))
            Label3.Text = "Debe Seleccionar un Período Válido";
        
        else
        {

           
            string imagepath = Server.MapPath("Img");
            
        DateTime desde = Convert.ToDateTime(TextBox1.Text);
        DateTime hasta = Convert.ToDateTime(TextBox2.Text);
       
        TimeSpan diff = hasta.Subtract(desde);
        int dias = diff.Days;

        if (dias < 0)
            Label3.Text = "Debe Seleccionar un Período Válido";

        else
        {
            
            String fecha = DateTime.Now.ToString("dd/MM/yyyy");

            int presup = 0;
            int total = 0;

            this.SqlDataSource2.DataSourceMode = SqlDataSourceMode.DataReader;
            SqlDataReader datos = (SqlDataReader)this.SqlDataSource2.Select(DataSourceSelectArguments.Empty);

            FileStream fs = new FileStream(Server.MapPath("~/") + "PRESUPUESTOS.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle rec3 = new Rectangle(PageSize.A4);
            Document doc = new Document(rec3, 5, 5, 5, 5);
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            iTextSharp.text.Font fontTitle = FontFactory.GetFont("Arial", 18, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font fontHead = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font fontBody = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            Console.WriteLine("");

            Paragraph titulo = new Paragraph("LISTADO DE PRESUPUESTOS AL " + fecha, fontTitle);
            titulo.Alignment = Element.ALIGN_JUSTIFIED;

            doc.Open();
            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(imagepath + "/logoaf.png");
            doc.Add(logo);
            doc.Add(titulo);
            doc.Add(new Paragraph("  "));
            doc.Add(new Paragraph("  "));
            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(7);
            table.HorizontalAlignment = 0;
            table.TotalWidth = 550f;
            table.LockedWidth = true;
            float[] widths = new float[] { 80f, 110f, 90f, 80f, 60f, 70f, 80f };
            table.SetWidths(widths);

            PdfPCell hnro = new PdfPCell(new Phrase("NRO.PRESUP.", new Font(fontHead)));
            PdfPCell hempresa = new PdfPCell(new Phrase("EMPRESA", new Font(fontHead)));
            PdfPCell hfechapresup = new PdfPCell(new Phrase("FECHA PRESUP.", new Font(fontHead)));
            PdfPCell hdetalle = new PdfPCell(new Phrase("DETALLE", new Font(fontHead)));
            PdfPCell himporte = new PdfPCell(new Phrase("IMPORTE", new Font(fontHead)));
            PdfPCell hestado = new PdfPCell(new Phrase("ESTADO", new Font(fontHead)));
            PdfPCell hvto = new PdfPCell(new Phrase("VENCIMIENTO", new Font(fontHead)));

            table.AddCell(hnro);
            table.AddCell(hempresa);
            table.AddCell(hfechapresup);
            table.AddCell(hdetalle);
            table.AddCell(himporte);
            table.AddCell(hestado);
            table.AddCell(hvto);
            doc.Add(new Paragraph("  "));
            while (datos.Read())
            {
                String numero = datos["nroPresupuesto"].ToString();
                String detalle = datos["detalle"].ToString();
                String razon = datos["razonSocial"].ToString();
                String importe = datos["importe"].ToString();
                String estado = datos["descripcionEstado"].ToString();
                String fechaPresup = datos["fechaPresupuesto"].ToString();
                String vto = datos["fechaValidez"].ToString();

                PdfPCell cnumero = new PdfPCell(new Phrase(numero, new Font(fontBody)));
                PdfPCell cdetalle = new PdfPCell(new Phrase(detalle, new Font(fontBody)));
                PdfPCell crazon = new PdfPCell(new Phrase(razon, new Font(fontBody)));
                PdfPCell cimporte = new PdfPCell(new Phrase("$ " + importe, new Font(fontBody)));
                PdfPCell cestado = new PdfPCell(new Phrase(estado, new Font(fontBody)));
                PdfPCell cfechapresup = new PdfPCell(new Phrase(fechaPresup, new Font(fontBody)));
                PdfPCell cvto = new PdfPCell(new Phrase(vto, new Font(fontBody)));
                DateTime entre = Convert.ToDateTime(fechaPresup);

                if ((desde <= entre)&&(entre <= hasta))
                {
                    table.AddCell(numero);
                    table.AddCell(razon);
                    table.AddCell(fechaPresup);
                    table.AddCell(detalle);
                    table.AddCell("$ " + importe);
                    table.AddCell(estado);
                    table.AddCell(vto);
               

                presup = presup + 1;
                int imp = Convert.ToInt32(importe);
                total = total + imp;

                }
            }
            doc.Add(table);
            doc.Add(new Paragraph("  "));
            doc.Add(new Paragraph("  "));
            doc.Add(new Paragraph("TOTAL DE PRESUPUESTOS: " + presup));
            doc.Add(new Paragraph("IMPORTE TOTAL: $" + total));
            doc.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment;filename=PRESUPUESTOS.pdf");
            Response.TransmitFile(Server.MapPath("~/") + "PRESUPUESTOS.pdf");
        }
        }
        }
    }
   
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        
        if (Label2.Text.Equals("desde"))
        {
                String date = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
                TextBox1.Text = date;
                Calendar1.Visible = false;

        }
        
        if (Label2.Text.Equals("hasta"))
        {

            String date = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
                TextBox2.Text = date;
                Calendar1.Visible = false;
             
        }
       
      

    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Calendar1.Visible = true;
        Label2.Text = "desde";
        Label3.Text = "";

    }


    protected void Button4_Click(object sender, EventArgs e)
    {
        Calendar2.Visible = true;
        Label2.Text = "hasta";
        Label3.Text = "";
    }

    protected void Calendar2_SelectionChanged(object sender, EventArgs e)
    {
        if (Label2.Text.Equals("desde"))
        {
            String date = Calendar2.SelectedDate.ToString("dd/MM/yyyy");
            TextBox1.Text = date;
            Calendar2.Visible = false;

        }

        if (Label2.Text.Equals("hasta"))
        {

            String date = Calendar2.SelectedDate.ToString("dd/MM/yyyy");
            TextBox2.Text = date;
            Calendar2.Visible = false;

        }
    }
    
    protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
    {
        string imagepath = Server.MapPath("Img");

        FileStream fs = new FileStream(Server.MapPath("~/") + "presupuesto" + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[1].Text + ".pdf", FileMode.Create, FileAccess.Write, FileShare.None);
        Rectangle rec3 = new Rectangle(PageSize.A4);
        Document doc = new Document(rec3, 10, 10, 10, 10);
        PdfWriter writer = PdfWriter.GetInstance(doc, fs);
        iTextSharp.text.Font fontTitle = FontFactory.GetFont("Arial", 18, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fontHead = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fontBody = FontFactory.GetFont("Arial", 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

        Console.WriteLine("");

        Paragraph titulo = new Paragraph("PRESUPUESTO: " + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[1].Text, fontTitle);
        titulo.Alignment = Element.ALIGN_JUSTIFIED;


        doc.Open();
        iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(imagepath + "/logoaf.png");
        doc.Add(logo);
        doc.Add(titulo);
        doc.Add(new Paragraph("  "));
        doc.Add(new Paragraph("  "));
        doc.Add(new Paragraph("-----------------------------------------------------------------------------------  "));
        doc.Add(new Paragraph(" "));
        doc.Add(new Paragraph("Empresa: " + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[2].Text));
        doc.Add(new Paragraph(" "));
        doc.Add(new Paragraph("Fecha de Presupuesto: " + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[3].Text));
        doc.Add(new Paragraph("Fecha de Validez: " + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[7].Text));
        doc.Add(new Paragraph(" "));
        doc.Add(new Paragraph("  "));
        doc.Add(new Paragraph("Detalle: " + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[4].Text));
        doc.Add(new Paragraph("                                                    Importe:  " + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[5].Text));
        doc.Add(new Paragraph("  "));
        doc.Add(new Paragraph("  "));
        doc.Add(new Paragraph("-----------------------------------------------------------------------------------"));

        doc.Close();

        GridView1.SelectedRow.Enabled = false;

        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment;filename=presupuesto" + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[1].Text + ".pdf");
        Response.TransmitFile(Server.MapPath("~/") + "presupuesto" + this.GridView1.Rows[this.GridView1.SelectedIndex].Cells[1].Text + ".pdf");



    }
}